package gold.digger;

import javafx.util.Pair;

/**
 * Created by fanzhenyu02 on 2020/6/27.
 * common problem solver template.
 */
public class LC224 {
    public long startExecuteTime = System.currentTimeMillis();


    class Solution {
        public int calculate(String s) {
            return calculateRecur(s, 0).getKey().intValue();
        }

        public Pair<Integer, Integer> calculateRecur(String s, int curPos) {
            if (curPos >= s.length() || s.charAt(curPos) == ')') {
                //遇到末尾或结尾括号
                return new Pair<>(0, curPos);
            }

            int i = curPos, curPartSum = 0, positive = 1;
            while (i < s.length()) {
                if (s.charAt(i) == ' ') {
                    ++i;
                    continue;
                }

                if (s.charAt(i) == ')') {
                    return new Pair<>(curPartSum, i + 1);
                }

                if (s.charAt(i) == '(') {
                    Pair nextPartRes = calculateRecur(s, i + 1);
                    curPartSum += positive * ((int) nextPartRes.getKey());
                    i = ((int) nextPartRes.getValue());
                    continue;
                }

                if (Character.isDigit(s.charAt(i))) {
                    int tempNum = 0;
                    while (i < s.length() && Character.isDigit(s.charAt(i))) {
                        tempNum = tempNum * 10 + s.charAt(i++) - '0';
                    }
                    curPartSum += positive * tempNum;
                    continue;
                } else {
                    positive = s.charAt(i++) == '+' ? 1 : -1;
                    continue;
                }
            }

            return new Pair<>(curPartSum, i);
        }
    }

    public void run() {
        Solution solution = new Solution();
        System.out.println(solution.calculate("(1+(4+5+2)-3)+(6+8)"));
    }

    public static void main(String[] args) throws Exception {
        LC224 an = new LC224();
        an.run();

        System.out.println("\ncurrent solution total execute time: " + (System.currentTimeMillis() - an.startExecuteTime) + " ms.");
    }
}
